<template>
  <h1>RTSP Stream</h1>
  <div>
    <img id="video-stream" :src="imageUrl" alt="RTSP Stream" style="max-width: 100%;" v-if="imageUrl">
  </div>
</template>

<script>
export default {
  props: {
    streamId: {
      type: Number,
      required: true
    }
  },
  data() {
    return {
      ws: null,
      imageUrl: '',
    };
  },
  mounted() {
    this.startWebSocket();
  },
  beforeDestroy() {
    if (this.ws) {
      this.ws.close();
    }
  },
  methods: {
    startWebSocket() {
      console.log(`Connecting to WebSocket for streamId: ${this.streamId}`); // 添加日志

      this.ws = new WebSocket(`ws://localhost:8000/ws/monitor/3/`);
      this.ws.binaryType = 'arraybuffer';

      this.ws.onopen = () => {
        console.log(`WebSocket ${this.streamId} connected`);
        this.$emit('ws-success', { streamId: this.streamId, status: 'connected' });
      };

      this.ws.onmessage = (event) => {
        const arrayBuffer = event.data;
        if (arrayBuffer) {
          const blob = new Blob([arrayBuffer], { type: 'image/jpeg' });
          const url = URL.createObjectURL(blob);
          this.imageUrl = url;
          setTimeout(() => URL.revokeObjectURL(url), 100);  // 延迟撤销 URL
        } else {
          console.error('Received empty ArrayBuffer');
        }
      };

      this.ws.onclose = (event) => {
        console.log(`WebSocket ${this.streamId} closed`);
        this.$emit('ws-closed', { streamId: this.streamId, status: 'closed', event });
        console.error('WebSocket closed:', event);
      };

      this.ws.onerror = (error) => {
        console.log(`WebSocket ${this.streamId} error`);
        this.$emit('ws-error', { streamId: this.streamId, status: 'error', error });
        console.error('WebSocket error:', error);
      };
    },
  },
};
</script>

<style scoped>
/* 可以在此处添加组件的样式 */
</style>
